package pers.qianyu.diytomcat.util;

import java.io.*;

/**
 * @author mizzle rain
 * @date 2021-01-07 10:56
 */
public class IOUtils {
    /**
     * 从输入流读取数据
     *
     * @param in    输入流
     * @param fully 是否全部读取
     * @return 内容字节数组
     * @throws IOException IO异常
     */
    public static byte[] readBytes(InputStream in, boolean fully) throws IOException {
        final int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int len = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
            if (!fully && len != bufferSize) {
                // 这一步非常关键，TCP链接不会发送关闭
                break;
            }
        }
        return baos.toByteArray();
    }
}
